// shop page
// ============

define(['zepto', 'utils'], 
function($, utils, JST) {
  return {
    init: function() {
      
      this.initPage()
      
    },
    
    initPage: function() {
      this.bindSubmit()
    },

    // order submit evvent handler
    bindSubmit: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-submit")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },

    // init data
    onInitData: function() {
      return {
        'name': {
          'value': $('input[name="name"]').val().trim(),
          'message': '姓名不能为空'
        },
        'mobile': {
          'value': $('input[name="mobile"]').val().trim(),
          'message': '手机不能为空'
        },
        'amount': {
          'value': $('input[name="amount"]').val().trim(),
          'message': '金额不能为空'
        }
      }
    },

    onValidateData: function(data) {
      var that = this;
      
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      if (data.amount.value == 0) {
        return $.toast('请填写正确的金额') 
      }
      
      if (!that.isMobile(data.mobile.value)) {
    	return $.toast('请输入正确的手机号码')
      }
      
      if (!that.isMoney(data.amount.value)) {
      	return $.toast('请输入正确的金额，小数点后1位')
        }

      return true
    },
    
    isMobile: function(mobile) {
      return mobile && /^((13)|(15)|(17)|(18))\d{9}$/.test(mobile)
    },
    
    isMoney: function(money) {
    	return money && /^[0-9]+([.]{1}[0-9])?$/.test(money);
    },

    onSubmitOrder: function(data) {
      var that = this;
      $.showPreloader('正在提交...')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/foundations/join',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('认领成功')
          setTimeout(function() {
             window.location.href = __CTX__.root + '/foundations/' + data.mobile.value;
          }, 1000)
        }, function(result) {
          $.toast(result.message || '认领失败')
        })
      })
    }
    
  }
})